package com.tnl.web.config.controller;

import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biz.hunter.dao.CompanyDAO;
import com.biz.hunter.dao.DomainDAO;
import com.biz.hunter.dao.EmployerDAO;
import com.biz.hunter.dao.TempCompanyDAO;
import com.biz.hunter.db.entity.Company;
import com.biz.hunter.db.entity.Domain;
import com.biz.hunter.db.entity.Employer;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.util.qualifiers.AuditIt;

import org.springframework.stereotype.Controller;

@Controller
public class TempCompanyController {
	private static final Logger logger = LoggerFactory.getLogger(TempCompanyController.class);
	
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private TempCompanyDAO tempCompanyDAO;
	@Autowired
	private EmployerDAO employerDAO;
	@Autowired
	private DomainDAO domainDAO;
	@Autowired
	private Authentication authentication;

	// 临时公司管理 (HR公司管理)
	@AuditIt(module = "Company", action = "company_view", description = "Show hrcompany index page")
	@RequestMapping(value = "admin/hrcompany/manage.page", method = RequestMethod.GET)
	public String tempCompanyManagement(HttpServletRequest request, Model model) {
		
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("UserId");

		logger.debug("userid is " + userId);
		if (!StringUtils.hasText(userId)) {
			logger.info("empty user id ,session is not initiallized.");
			return "admin/platformadminlogin";
		}

		AdminUser user = authentication.getCurrentUser();
		if (user == null) {
			logger.error("can not get the user info" + userId);
			return "admin/platformadminlogin";
		}
		
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		return "admin/employer/hrcompanylist";
	}
	
	// 显示编辑表单页面
	@AuditIt(module = "Company", action = "editCompany", description = "Show edit company page")
	@RequestMapping(value = "admin/hrcompany/form.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, Model model) {

		String companyid = request.getParameter("companyid");
		Company cp = null;
		if (StringUtils.hasText(companyid)) {
			cp = tempCompanyDAO.getById(Integer.parseInt(companyid));
			model.addAttribute("company", cp);
		} else {
			return "admin/errorpage";
		}
		
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		return "admin/employer/hrcompanyeditform";
	}

	// 显示公司详细信息页面
	@RequestMapping(value = "admin/hrcompany/detail.page", method = RequestMethod.GET)
	public String hrCompanyDetail(HttpServletRequest request, Model model) {

		String companyid = request.getParameter("companyid");
		
		Company cp = null;
		if (StringUtils.hasText(companyid)) {
			cp = tempCompanyDAO.getById(Integer.parseInt(companyid));
			model.addAttribute("company", cp);
		} else {
			return "admin/errorpage";
		}
		
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		return "admin/employer/hrcompanydetail";
	}

	// 搜索数据
	@RequestMapping(value = "admin/hrcompany/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<Company> searchHrCompany(jqGridRequestObject request, String sname, String sphone, Integer sstatus) {
		
		jqGridResponseObject<Company> msg = new jqGridResponseObject<Company>();
		
		long page = request.getPage();
		long pagesize = request.getRows();
		
		long totalrows = request.getTotalrows();
		long totalpages = 0;
		
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = tempCompanyDAO.getCountOfAll(sname, sphone);
		}
		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
		
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;
		
		List<Company> list = tempCompanyDAO.getAllWithLimit(sname, sphone, start, pagesize);
		
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
		
		return msg;
	}
	
	// 认证
	@AuditIt(module = "Company", action = "editCompany", description = "Edit company action")
	@RequestMapping(value = "admin/hrcompany/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateHrCompany(HttpServletRequest request,  Company company) {
		
		ErrorMsg msg = new ErrorMsg();
		
		if(company == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司信息");
			return msg;
		}
		if(company.getId() <= 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司信息");
			return msg;
		}
		int oldtempcompanyid = company.getId();
		
		Company cp = tempCompanyDAO.getById(company.getId());
		if(cp == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该公司");
			return msg;
		}
		int employerid = cp.getEmployerid();
		if(employerid <0) {
			msg.setErrorcode("500101");
			msg.setMsg("数据出错，请联系管理员");
			return msg;
		}
		Employer employer = employerDAO.getById(employerid);
		if(employer == null) {
			msg.setErrorcode("500101");
			msg.setMsg("数据出错，请联系管理员");
			return msg;
		}
		String companyname = company.getName();
		Company newcompany = companyDAO.getByName(companyname);
		
		if(newcompany != null) {
			// 公司名已经在company中存在
			msg.setErrorcode("1");
			msg.setErrorcode("该公司名称已经存在，使用该存在的公司吗？");
			msg.setData(company.getId());
			return msg;
		}
		
		//创建新的公司并替换
		cp.setName(company.getName());
		cp.setContact(company.getContact());
		cp.setPhone(company.getPhone());
		cp.setAddress(company.getAddress());
		cp.setApproved(1);
		cp.setLicenseCode(company.getLicenseCode());
		cp.setOrgnizationCode(company.getOrgnizationCode());
		cp.setDomain(company.getDomain());
		cp.setId(0);

		int result = companyDAO.save(cp);
		if (result < 0 ) {
			msg.setErrorcode("5001");
			msg.setMsg("创建新公司失败");
			return msg;
		}
		cp.setId(result);
		
		tempCompanyDAO.delete(String.valueOf(oldtempcompanyid));
		
		employer.setCompanyId(cp.getId());
		employer.setCompanyName(cp.getName());
//		employer.setBinded(0);
		
		result = employerDAO.update(employer);
		if(result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新HR信息失败");
			return msg;
		}
		
		msg.setErrorcode("0");
		msg.setMsg("认证成功");
		return msg;
	}
	
	// 替换公司
	@AuditIt(module = "Company", action = "editCompany", description = "Substiute company action")
	@RequestMapping(value = "admin/hrcompany/substiute.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg substituteHrCompany(HttpServletRequest request, Integer companyid) {
			
		ErrorMsg msg = new ErrorMsg();
		
		if(companyid == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司信息");
			return msg;
		}
		if(companyid <= 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司信息");
			return msg;
		}
		int oldtempcompanyid = companyid;
		
		// 得到该公司
		Company cp = tempCompanyDAO.getById(companyid);
		if(cp == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该公司");
			return msg;
		}
		int employerid = cp.getEmployerid();
		if(employerid <0) {
			msg.setErrorcode("500101");
			msg.setMsg("数据出错，请联系管理员");
			return msg;
		}
		Employer employer = employerDAO.getById(employerid);
		if(employer == null) {
			msg.setErrorcode("500101");
			msg.setMsg("数据出错，请联系管理员");
			return msg;
		}
		
		String companyname = cp.getName();
		Company newcompany = companyDAO.getByName(companyname);
		
		if(newcompany == null) {
			// 不存在公司
			msg.setErrorcode("5001");
			msg.setErrorcode("不存在公司");
			return msg;
		}
				
		tempCompanyDAO.delete(String.valueOf(oldtempcompanyid));
		
		employer.setCompanyId(newcompany.getId());
		employer.setCompanyName(newcompany.getName());
		
		int result = employerDAO.update(employer);
		if(result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新HR信息失败");
			return msg;
		}
		
		msg.setErrorcode("0");
		msg.setMsg("认证成功");
		return msg;
	}

	// 删除数据
	@AuditIt(module = "Company", action = "deleteCompany", description = "Delete company action")
	@RequestMapping(value = "admin/hrcompany/delete.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg deleteHrCompany(HttpServletRequest request, Integer companyid) {
			
		ErrorMsg msg = new ErrorMsg();
			
		if (companyid == null) {
			logger.debug("companyid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}

		int result = tempCompanyDAO.delete(String.valueOf(companyid));
		if (result == 1) {
			msg.setErrorcode("0");
			msg.setMsg("删除成功");
			return msg;
		}

		msg.setErrorcode("50001");
		msg.setMsg("删除失败");
		return msg;
	}

	/*
	@RequestMapping(value = "admin/tempcompany/toView.page", method = RequestMethod.GET)
	public Company getCompanyDetail(
			@RequestParam(value = "id", required = false, defaultValue = "0") Integer id) {
		Company company = tempCompanyDAO.getById(id);
		return company;
	}

	@RequestMapping(value = "admin/tempcompany/getAllCompany.do", method = RequestMethod.GET)
	@ResponseBody
	public JqGridPage getAllCompany(JqGridPage page) {
		List<Company> list = tempCompanyDAO.getALL();
		Page<Company> companies = new PageImpl<Company>(list,
				page.toPageable(), list.size());
		page = JqGridPage.valueOf(companies);
		return page;
	}
	
	@RequestMapping(value = "admin/tempcompany/manage.page", method = RequestMethod.GET)
	public String getCompanies(ModelMap model) {
		List<Company> list = tempCompanyDAO.getALL();
		model.addAttribute("tempCompanies", list);
		return "admin/tempcompany/list";
	}


	@ResponseBody
	@RequestMapping(value = "admin/tempcompany/getDomainCompanies", method = RequestMethod.GET)
	public List<Company> getDomainCompanies(
			@RequestParam(value = "domainId", required = true, defaultValue = "0") Integer domainId) {
		List<Company> list = companyDAO.getDomainCompanies(domainId);
		return list;
	}

	@RequestMapping(value = "admin/tempcompany/create.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg createCompany(@RequestBody Company company) {
		logger.info("Start create Company.");
		ErrorMsg msg = new ErrorMsg();
		Date now = new Date();
		company.setCreateDate(now.getTime());
		int result = tempCompanyDAO.save(company);
		if (result == -1) {
			logger.error("create company failed" + company);
			return null;
		}

		company.setId(result);
		return msg;
	}

	@RequestMapping(value = "admin/tempcompany/deactiveCompany.do", method = RequestMethod.DELETE)
	public @ResponseBody ErrorMsg deactiveCompany(@PathVariable("id") int Id) {
		logger.info("Start delete Company.");
		ErrorMsg msg = new ErrorMsg();
		Company company = tempCompanyDAO.getById(Id);
		company.setApproved(-1);
		tempCompanyDAO.update(company);
		return msg;
	}

	@RequestMapping(value = "admin/tempcompany/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateCompany(@RequestBody Company company) {
		logger.info("Start UPDATE Company.");
		ErrorMsg msg = new ErrorMsg();
		Company current = tempCompanyDAO.getById(company.getId());
		convertCompany(company, current);
		tempCompanyDAO.update(current);
		return msg;
	}

	private void convertCompany(Company srcCompany, Company destCompany) {
		destCompany.setContact(srcCompany.getContact());
		destCompany.setEmail(destCompany.getEmail());
		// ... TODO：

	}

	// 认证一个公司，就是把temp公司转为公司的过程。
	@RequestMapping(value = "admin/tempcompany/Authorize.do", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> authorizeCompany(
			HttpServletRequest request, int hunterId, int tempId, int companyId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Employer employer = employerDAO.getById(hunterId);
		if (employer == null) {
			map.put("errorcode", "500");
			map.put("msg", "can not find the hunter with the provided id ="
					+ hunterId);
			return map;
		}
		//if (employer.getCompanyId() != 0) {
		//	map.put("errorcode", "500");
		//	return map;
		//}
		if (!StringUtils.hasText(employer.getCompanyName())) {
			map.put("errorcode", "500");
			return map;
		}

		Company tempCompany = tempCompanyDAO.getById(tempId);
		if (employer.getCompanyId() != 0) {
			map.put("errorcode", "500");
			return map;
		}

		Company company = companyDAO.getById(companyId);
		if (company == null) {
			int id = companyDAO.save(tempCompany);
			if (id != -1) {
				tempCompanyDAO.deleteById(tempId);
			}
			employer.setCompanyName(null);
			employer.setCompanyId(id);
			employerDAO.update(employer);
			map.put("errorcode", "200");
			map.put("msg", "success");
			return map;
		} else {

			employer.setCompanyName(null);
			employer.setCompanyId(companyId);
			employerDAO.update(employer);
			map.put("errorcode", "200");
			map.put("msg", "success");
			return map;
		}
	}

	// 认证一个公司，就是把temp公司转为公司的过程。
	@RequestMapping(value = "admin/tempcompany/mergeCompany.do", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> mergeCompany(
			HttpServletRequest request, int hunterId, int tempId, int companyId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("errorcode", "200");
		map.put("msg", "success");
		return map;
	}
	
	
	@RequestMapping(value = "wechat/tempcompany/create.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> persistentCompany(
			HttpServletRequest request, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("openId");

		int hrId = dto.getHrid();
		if (hrId == 0) {
			logger.error("the input hr id is 0");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hrId");
			return returnMap;
		}
		Employer employer = employerDAO.getById(hrId);
		if (employer == null) {
			logger.error("can not get the employer by the provided id" + hrId);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hr id = "
					+ hrId);
			return returnMap;
		}

		int companyId = persistentCompany(dto);
		if (companyId == -1) {
			logger.error("failed to persistent Company");
			returnMap.put("errorcode", "50105");
			returnMap.put(
					"msg",
					" failed to persistent the  company ("
							+ dto.getCompanyname() + ")  Id ="
							+ dto.getCompanyid());
			returnMap.put("data", companyId);
			return returnMap;
		}
		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}
	
	private int persistentCompany(CompanyDto dto) {
		int companyId = dto.getCompanyid();

		Company comp = tempCompanyDAO.getById(companyId);
		if (comp != null) {// update
			// 认证通过，不再update
			if (comp.getApproved() == 1) {
				return companyId;
			}
			comp.setName(dto.getCompanyname());
			comp.setContact(dto.getCompanycontact());
			comp.setAddress(dto.getCompanyaddress());
			// comp.setEmail(dto.);
			comp.setPhone(dto.getCompanyphone());
			comp.setLicenseCode(dto.getBizcode());
			comp.setOrgnizationCode(dto.getOrgcode());
			comp.setCreateId(dto.getHrid());
			int result = tempCompanyDAO.update(comp);
			if (result == -1) {
				logger.error("failed to update hunter comapny" + companyId);
				return -1;
			}
			return companyId;
		}
		int hrId = dto.getHrid();
		comp = tempCompanyDAO.getByEmployerId(hrId);
		if (comp != null) {
			logger.error("ther user has already created one company.");
			return -1;
		}
		// create new company
		comp = new Company();
		comp.setName(dto.getCompanyname());
		comp.setContact(dto.getCompanycontact());
		comp.setAddress(dto.getCompanyaddress());
		// comp.setEmail(dto.);
		comp.setPhone(dto.getCompanyphone());
		comp.setLicenseCode(dto.getBizcode());
		comp.setOrgnizationCode(dto.getOrgcode());
		comp.setApproved(0);
		Date now = new Date();
		comp.setCreateDate(now.getTime());
		comp.setCreateId(dto.getHrid());
		int result = tempCompanyDAO.save(comp);
		if (result == -1) {
			logger.error("failed to update hunter comapny" + comp.getName());
			return -1;
		}
		// companyId = comp.getId();

		return result;
	}
	*/
}